package com.gsj.system.service.impl;

import com.gsj.common.pojo.R;
import com.gsj.common.utils.JwtUtils;
import com.gsj.system.config.RsaKeyProperties;
import com.gsj.system.eneity.Client;
import com.gsj.system.mapper.ClientMapper;
import com.gsj.system.pojo.ClientVo;
import com.gsj.system.service.ClientService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: clms-eighth01
 * @description:
 * @author: 张巍蓝
 * @create: 2021-07-30 17:16
 **/
@Service
public class ClientServiceImpl implements ClientService {
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private RsaKeyProperties rsaKeyProperties;
    @Override
    public R login(String username,String password ) {
        Subject subject = SecurityUtils.getSubject();
        //调用login方法
        UsernamePasswordToken usernameToken = new UsernamePasswordToken(username, password);
        try{
            subject.login(usernameToken);
        }
        catch (UnknownAccountException e){
            System.out.println("用户名不对！！！！");
            R.error();
        }catch (IncorrectCredentialsException credentialsException){
            System.out.println("密码不对！！！");
            R.error();
        }
        Client u =(Client)subject.getPrincipal();
        System.out.println(u);
        Client user = new Client();
        user.setId(u.getId());
        user.setStatus(u.getStatus());
        user.setName(u.getName());
        String token = JwtUtils.generateTokenExpireInMinutes(user,rsaKeyProperties.getPrivateKey(),24 * 60);
        return R.ok().put("token",token).put("message","登陆成功").put("userid",u.getId());
    }

    @Override
    public R queryClientrbyid(Integer userid) {
        List<Client> clients = clientMapper.queryClientrbyid(userid);
        return R.ok().put("clients",clients).put("message","成功");
    }
}
